package com.durian.auth.service;

import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.tea.TeaException;
import com.aliyun.teautil.models.RuntimeOptions;
import com.durian.common.core.constant.AliConstants;
import com.durian.common.core.domain.R;
import com.durian.common.core.utils.SmsUtils;
import com.durian.common.redis.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * 阿里云短信
 * @author 123
 */
@Component
public class SmsService {

    @Autowired
    RedisService redisService;

    /**
     * 发送短信
     * @param phonenumber
     * @return
     * @throws Exception
     */
    public R<?> sendMsg(String phonenumber,String key) throws Exception {
        String code = SmsUtils.aliCode();
        com.aliyun.dysmsapi20170525.Client client = SmsUtils.createClient(
                AliConstants.ACCESS_KEY_ID,  AliConstants.ACCESS_KEY_SECRET);
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setSignName(AliConstants.SIGN_NAME)
                .setTemplateCode(AliConstants.TEMPLATE_CODE)
                .setPhoneNumbers(phonenumber)
                .setTemplateParam("{\"code\":\""+code+"\"}");
        RuntimeOptions runtime = new RuntimeOptions();
        try {
            // 复制代码运行请自行打印 API 的返回值
            SendSmsResponse response = client.sendSmsWithOptions(sendSmsRequest, runtime);
            redisService.setCacheObject(AliConstants.ALI_MSG_CODE +key,code, AliConstants.ALI_EXPIRE_TIME, TimeUnit.MINUTES);
            return R.ok();
        } catch (TeaException error) {
            // 如有需要，请打印 error
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 如有需要，请打印 error
            com.aliyun.teautil.Common.assertAsString(error.message);
        }
        return R.fail();
    }
}
